package com.fiona.core.load;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fiona.annotation.FionaInterceptor;
import com.fiona.common.constant.FionaConstant;
import com.fiona.common.constant.FionaSpace;
import com.fiona.core.model.FionaBeanClassModel;
import com.fiona.core.model.FionaInterModel;

/**
 * 加载拦截器
 */
public class LoadInters {

    private static Logger log = LoggerFactory.getLogger(LoadInters.class);

    /**
     * 获取全局存储空间
     */
    private static FionaSpace constants = FionaSpace.getFionaSpace();

    /**
     * 创建所有拦截器对象
     */
    public static void loadIntersList() {
        try {
            List<FionaInterModel> list = new ArrayList<>();

            List<FionaBeanClassModel> interceptors = LoadHelper.getInterceptorList();

            for (FionaBeanClassModel fionaBeanClassModel : interceptors) {

                FionaInterceptor interceptor = (FionaInterceptor) fionaBeanClassModel.getAnnotation();
                String pattern = interceptor.pattern();
                Class cls = fionaBeanClassModel.getClassName();

                FionaInterModel fionaInterModel = new FionaInterModel();
                fionaInterModel.setCls(cls);
                fionaInterModel.setObj(cls.getDeclaredConstructor().newInstance());
                fionaInterModel.setPattern(pattern.toUpperCase());

                /* 给拦截器注入属性 */
                WriteFields.writeFields(cls, fionaInterModel.getObj(), LoadHelper.getBeanObjectMap());

                list.add(fionaInterModel);
            }
            constants.setAttr(FionaConstant.INTERCEPTOR_OBJECTS, list);

        } catch (Exception e) {
            log.error("读取拦截器报错", e);
        }
    }
}
